package com.lyp.lease.web.admin.controller.user;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyp.lease.common.result.Result;
import com.lyp.lease.model.entity.UserInfo;
import com.lyp.lease.model.enums.BaseStatus;
import com.lyp.lease.web.admin.service.UserInfoService;
import com.lyp.lease.web.admin.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "用户信息管理")
@RestController
@RequestMapping("/admin/user")
public class UserInfoController {
    @Autowired
    UserInfoService userInfoService;
    @Operation(summary = "分页查询用户信息")
    @GetMapping("page")
    public Result<IPage<UserInfo>> pageUserInfo(@RequestParam long current, @RequestParam long size, UserInfoQueryVo queryVo) {
        // 在这写这种代码没用，参数转换错误就会报错，执行不到这里
        if (queryVo.getStatus() !=null) {
            if (queryVo.getStatus() != BaseStatus.DISABLE && queryVo.getStatus() != BaseStatus.ENABLE){
                // Controller层抛出的异常会让全局异常处理器捕获然后处理
                throw new IllegalArgumentException("用户状态只能是1或者0,1是正常,0是禁用");
            }
        }

        LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userInfoLambdaQueryWrapper.like(UserInfo::getPhone,queryVo.getPhone());
        userInfoLambdaQueryWrapper.eq(UserInfo::getStatus,queryVo.getStatus());

        Page<UserInfo> page = userInfoService.page(new Page<>(current,size),userInfoLambdaQueryWrapper);


        return Result.ok(page);
    }

    @Operation(summary = "根据用户id更新账号状态")
    @PostMapping("updateStatusById")
    public Result updateStatusById(@RequestParam Long id, @RequestParam BaseStatus status) {
        LambdaUpdateWrapper<UserInfo> userInfoLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        userInfoLambdaUpdateWrapper.eq(UserInfo::getId,id);
        userInfoLambdaUpdateWrapper.set(UserInfo::getStatus,status);
        userInfoService.update(userInfoLambdaUpdateWrapper);

        return Result.ok();
    }
}
